<?php

namespace App\GraphQL\Mutations\FactoryDevice;

use App\Models\FactoryDevice;
use App\Models\FactoryStatistical;
use GraphQL\Type\Definition\ResolveInfo;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
class Delete
{
    /**
     * Return a value for the field.
     *
     * @param  null  $rootValue Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param  mixed[]  $args The arguments that were passed into the field.
     * @param  \Nuwave\Lighthouse\Support\Contracts\GraphQLContext  $context Arbitrary data that is shared between all fields of a single query.
     * @param  \GraphQL\Type\Definition\ResolveInfo  $resolveInfo Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        $oldDevice = $this->validate($args['id']);
        $oldDevice->delete();
        $statistical = FactoryStatistical::firstOrCreate(['user_id'=>$oldDevice->user_id]);
        $statistical->increment('total_device');
        return [
            'status'=> '200',
            'message'=>'设备删除成功'
        ];
    }
    public function validate($id)
    {
        $authUser = auth()->user();
        $old = FactoryDevice::find($id);
        if ($old) {
            // 如果已经归档并发货则不能删除
            if($old->status === 'READONLY'){
                throw new \Exception('设备已经出厂不能删除!');
            }
            
            if ($authUser->role_code !== 'ADMIN' && $old->user_id !== $authUser->id) {
                throw new \Exception('没有权限设备不能删除!');
            }
            return $old;
        }
        throw new \Exception('设备不存在!');
    }
}
